package com.yfq.springframework.beans.support;

import com.yfq.springframework.beans.config.BeanDefinition;
import com.yfq.springframework.exception.BeansException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 姚凤桥
 * @date 2022/11/22 16:13
 * @description 使用jdk反射创建对象
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(String beanName, BeanDefinition beanDefinition, Constructor<?> constructor, Object... args) {
        try {
            if (constructor != null) {
                return constructor.newInstance(args);
            } else {
                //如果没有指定构造函数，默认使用无参构造
                return beanDefinition.getBeanClass().newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("创建名为[" + beanName + "]的bean出现错误！");
        }
    }
}
